from datetime import datetime
import json
import traceback
from django.http import JsonResponse
from django.views.generic import View
from ..models.basicDimensionModel import *
from ..serializers.basicDimensionSerializer import *
from django.db.models import Q, Count
from django.core.paginator import Paginator
from utils.encryptionAndDecryptionUtil import get_user_from_useraccount, get_useraccount_from_request
from ..config.message_config import *
from ..utils.common_util.basic_util import get_order_list_combined
from ..utils.related_util.used_util import is_basic_dimension_used
from utils.responseContentUtil import *


class BasicDimensionView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = request.GET
            query_list_serializer = BasicDimensionListQuerySerializer(
                data=data)
            data_valid = query_list_serializer.is_valid()
            if not data_valid:
                return make_get_error_response(message=query_list_serializer.errors)
            data = query_list_serializer.validated_data
            query = Q()
            query &= Q(valid_flag=True)
            if "basic_dimension_name" in data:
                query &= (Q(
                    basic_dimension_name__icontains=data["basic_dimension_name"]) | Q(basic_dimension_name_en__icontains=data["basic_dimension_name"]))
            if "sei_id" in data:
                query &= Q(sei_id__icontains=data["sei_id"])
            if "basic_dimension_symbol" in data:
                query &= (Q(
                    basic_dimension_symbol__icontains=data["basic_dimension_symbol"]) | Q(basic_dimension_symbol_ascii__icontains=data["basic_dimension_symbol"]) | Q(basic_dimension_symbol_html__icontains=data["basic_dimension_symbol"]) | Q(basic_dimension_symbol_latex__icontains=data["basic_dimension_symbol"]) | Q(basic_dimension_symbol_unicode__icontains=data["basic_dimension_symbol"]))
            order_list_combined = get_order_list_combined(data)
            if len(order_list_combined) == 0:
                basic_dimensions = BasicDimension.objects.filter(
                    query).order_by("-create_date")
            else:
                basic_dimensions = BasicDimension.objects.filter(
                    query).order_by(*order_list_combined)
            page_size = data["page_size"]
            current_page = data["current_page"]
            total_count = basic_dimensions.count()
            paginator = Paginator(basic_dimensions, page_size)
            if current_page > paginator.num_pages:
                current_page = paginator.num_pages
            page_obj = paginator.get_page(current_page)
            res_data = {}
            res_data["current_page"] = current_page
            res_data["page_size"] = page_size
            res_data["total_count"] = total_count
            basic_dimension_list_serializer = BasicDimensionListSerializer(
                page_obj, many=True)
            res_data["objects"] = basic_dimension_list_serializer.data
            return make_get_success_response(data=res_data)

        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))

    def post(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            user_name = get_user_from_useraccount(user_name)
            data = json.loads(request.body)
            create_serializer = BasicDimensionCreateSerializer(data=data)
            data_valid = create_serializer.is_valid()
            if not data_valid:
                res_message = "参数错误：\n"
                if "sei_id" in create_serializer.errors:
                    res_message += "编码已存在;\n"
                if "basic_dimension_name" in create_serializer.errors:
                    res_message += "基本量纲中文名称已存在;\n"
                if "basic_dimension_name_en" in create_serializer.errors:
                    res_message += "基本量纲英文名称已存在;\n"
                return make_create_error_response(message=res_message)
            
            data = create_serializer.validated_data
            data["create_person"] = user_name
            data["modify_person"] = user_name
            basic_dimension = BasicDimension.objects.create(**data)
            return make_create_success_response(data=None)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))


class BasicDimensionInfoView(View):
    def get(self, request, uuid):
        res = {"code": 400, "message": "", "data": None}
        try:
            get_params = request.GET
            info_get_type = get_params.get("type", "")
            basic_dimension = BasicDimension.objects.filter(
                uuid=uuid, valid_flag=True).first()
            if basic_dimension is None:
                return make_get_error_response(message="该条目不存在")
            if info_get_type == "modify":
                basic_dimension_serializer = BasicDimensionModifyInfoSerializer(
                    basic_dimension)
            else:
                basic_dimension_serializer = BasicDimensionInfoSerializer(
                    basic_dimension)
            return make_get_success_response(data=basic_dimension_serializer.data)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))

    def put(self, request, uuid):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            user_name = get_user_from_useraccount(user_name)
            data = json.loads(request.body)
            basic_dimension = BasicDimension.objects.filter(
                uuid=uuid, valid_flag=True).first()
            if basic_dimension is None:
                return make_update_error_response(message="该条目不存在")
            modify_serializer = BasicDimensionModifyInfoInSerializer(
                basic_dimension, data=data)
            data_valid = modify_serializer.is_valid()
            if not data_valid:
                res_message = "参数错误：\n"
                if "sei_id" in modify_serializer.errors:
                    res_message += "编码已存在;\n"
                if "basic_dimension_name" in modify_serializer.errors:
                    res_message += "基本量纲中文名称已存在;\n"
                if "basic_dimension_name_en" in modify_serializer.errors:
                    res_message += "基本量纲英文名称已存在;\n"
                return make_update_error_response(message=res_message)
            data = modify_serializer.validated_data
            data["modify_person"] = user_name
            for field, value in data.items():
                setattr(basic_dimension, field, value)
            basic_dimension.save()
            return make_update_success_response(data=None)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))

    def delete(self, request, uuid):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            user_name = get_user_from_useraccount(user_name)
            basic_dimension = BasicDimension.objects.filter(
                uuid=uuid, valid_flag=True).first()
            if not basic_dimension:
                return make_delete_error_response(message="该条目不存在")
            used_flag, used_message = is_basic_dimension_used(basic_dimension)
            if used_flag:
                return make_delete_error_response(message=used_message)
            basic_dimension.valid_flag = False
            basic_dimension.modify_person = user_name
            basic_dimension.save()
            return make_delete_success_response(data=None)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))
